<?php
// --- init
session_start();


// --- func
function conn() {
	static $pdo = null;
	if ($pdo == null) {
		$pdo = new PDO("mysql:host=127.0.0.1;dbname=test;charset=utf8", "root", "123456", array(
			PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
		));
	}
	return $pdo;
}

function select($table, $where = "") {
	if ($where != "") {
		$where = " WHERE $where";
	}
	$sql = "SELECT * FROM $table$where";
	$stmt = conn()->prepare($sql);
	$stmt->execute();
	return $stmt->fetch();
}

function select_all($table, $where = "") {
	if ($where != "") {
		$where = " WHERE $where";
	}
	$sql = "SELECT * FROM $table$where";
	$stmt = conn()->prepare($sql);
	$stmt->execute();
	return $stmt->fetchAll();
}

function insert($table, $data) {
	$cols = implode(",", array_keys($data));
	$vals = implode("','", array_values($data));
	$sql = "INSERT INTO $table ($cols) VALUES ('$vals');";
	$stmt = conn()->prepare($sql);
	$stmt->execute();
	return $stmt;
}

function update($table, $data, $where = "") {
	if ($where != "") {
		$where = " WHERE $where";
	}

	$sets = array();
	foreach ($data as $col => $val) {
		$sets[] = "$col = '$val'";
	}
	$sets = implode(",", $sets);
	$sql = "UPDATE $table set $sets$where";
	$stmt = conn()->prepare($sql);
	$stmt->execute();
	return $stmt;
}

function delete($table, $where = "") {
	if ($where != "") {
		$where = " WHERE $where";
	}
	$sql = "DELETE FROM $table$where";
	$stmt = conn()->prepare($sql);
	$stmt->execute();
	return $stmt;
}

function lastInsertId() {
	return conn()->lastInsertId();
}

// ----

function save($table, $data) {
	if (array_key_exists("id", $data)) {
		$id = $data["id"];
		unset($data["id"]);
		update($table, $data, "id = $id");
	} else {
		insert($table, $data);
	}
}

function login() {
	if (empty($_SESSION['user'])) {
		header("Location: login.html?url=".urlencode("http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]));
		exit();
	}
}

function redirect($url) {
	header("Location: $url");
	exit();
}